﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using E5_KhuyenMaiVang.Models;
using System.Web.Security;

namespace E5_KhuyenMaiVang.Controllers
{
    public class CompanyController : Controller
    {
        GoldDealEntities db = new GoldDealEntities();

        [Authorize(Roles = "Company")]
        public ActionResult AddDeal()
        {
            ViewBag.CategoryID = new SelectList(db.CATEGORY, "CategoryID", "CategoryName");
            ViewBag.CityID = new SelectList(db.CITY, "CityID", "CityName");
            return View();
        }

        [Authorize(Roles = "Company")]
        [HttpPost]
        public ActionResult AddDeal(DEAL deal)
        {
            if (ModelState.IsValid)
            {
                deal.StatusID = 1;
                MembershipUser user = Membership.GetUser((string)Session["LogOn"]);
                deal.CompanyID = db.COMPANY.Single(c => c.Account == (Guid)user.ProviderUserKey).CompanyID;
                db.DEAL.AddObject(deal);
                db.SaveChanges();
                return RedirectToAction("../Home/Index");
            }
            ViewBag.CategoryID = new SelectList(db.CATEGORY, "CategoryID", "CategoryName", deal.CategoryID);
            ViewBag.CityID = new SelectList(db.CITY, "CityID", "CityName", deal.CityID);
            return View(deal);
        }

        [Authorize(Roles = "Company")]
        public ActionResult Edit()
        {
            MembershipUser user = Membership.GetUser((string)Session["LogOn"]);
            COMPANY c = db.COMPANY.First(a => a.Account == (Guid)user.ProviderUserKey);            
            CompanyView cv = CompanyManager.ToCompanyView(c);            
            return View(cv);
        }

        [Authorize(Roles = "Company")]
        [HttpPost]
        public ActionResult Edit(CompanyView cv)
        {
            MembershipUser user = Membership.GetUser((string)Session["LogOn"]);
            COMPANY c = db.COMPANY.First(a => a.Account == (Guid)user.ProviderUserKey);
            CompanyManager.ToCompany(c, cv);
            db.SaveChanges();
            return PartialView("EditSuccess");
        }

        public ActionResult Create()
        {
            return View();
        }

        [Authorize(Roles = "Company")]
        public ActionResult DealHistory()
        {
            return View(getAllDeal());
        }

        private List<DEAL> getAllDeal()
        {
            ViewBag.DealStatuses = db.DEAL_STATUS;
            MembershipUser user = Membership.GetUser((string)Session["LogOn"]);
            COMPANY company = db.COMPANY.First(c => c.Account == (Guid)user.ProviderUserKey);
            List<DEAL> deals = db.DEAL.Where(d => d.CompanyID == company.CompanyID).ToList();
            return deals;
        }

        [Authorize(Roles = "Company")]
        public ActionResult VoucherManager()
        {
            return View(getAllVouchers());
        }

        [Authorize(Roles = "Company")]
        [HttpPost]
        public ActionResult Search(int Status = 0, string DealName = "")
        {
            List<DEAL> deals = new List<DEAL>();
            if (Status != 0)
                deals = getAllDeal().Where(p => p.DealName.Contains(DealName) && p.StatusID == Status).ToList();
            else
                deals = getAllDeal().Where(p => p.DealName.Contains(DealName)).ToList();
            return View("DealHistory", deals);

        }

        [Authorize(Roles = "Company")]
        [HttpPost]
        public ActionResult SearchVoucher(int DealID = 0, int StatusID = 0, string MemberName = "", int VoucherID = 0)
        {
            List<VOUCHER> temp = new List<VOUCHER>();
            if (VoucherID != 0)
            {
                temp.Add(getAllVouchers().First(v => v.VoucherID == VoucherID));
            }
            else
            {
                if (DealID != 0)
                {
                    temp = getAllVouchers().Where(v => v.DealID == DealID).ToList();
                }
                else
                {
                    temp = getAllVouchers();
                }
                if (StatusID != 0)
                {
                    temp = temp.Where(v => v.StatusID == StatusID).ToList();
                }
                temp = temp.Where(v => v.MEMBER.MemberName.Contains(MemberName)).ToList();
            }
            return View("VoucherManager", temp);
        }

        [HttpPost]
        [Authorize(Roles = "Company")]
        public ActionResult UpdateStatus(int VoucherStatus = 0, int VoucherID = 0)
        {
            if (VoucherStatus != 0 && VoucherID != 0)
            {
                VOUCHER updatevoucher = db.VOUCHER.First(v => v.VoucherID == VoucherID);
                updatevoucher.StatusID = VoucherStatus;

                db.SaveChanges();
            }
            return View("VoucherManager", getAllVouchers());
        }

        private List<VOUCHER> getAllVouchers()
        {
            ViewBag.Deals = getAllDeal();
            ViewBag.Statuses = db.DEAL_STATUS;
            ViewBag.VoucherStatuses = db.VOUCHER_STATUS;
            List<VOUCHER> vouchers = new List<VOUCHER>();
            foreach (var item in getAllDeal())
            {
                vouchers.AddRange(db.VOUCHER.Where(v => v.DealID == item.DealID));
            }
            return vouchers;
        }

        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Register(CompanyView company)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Insert vào membership
                    MembershipCreateStatus createStatus;
                    MembershipUser user = Membership.CreateUser(company.Username, company.Password, company.Email, null, null, true, null, out createStatus);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        CompanyManager.AddCompany(company, (Guid)user.ProviderUserKey);
                        Roles.AddUsersToRole(new string[] { company.Username }, "Company");
                        FormsAuthentication.SetAuthCookie(company.Username, false /* createPersistentCookie */);
                        return PartialView("_resultRegister");
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }
                    
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
            }

            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

    }
}
